/// Copyright (c) Microsoft Corporation.  All rights reserved.
using System;
using System.Windows.Forms;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace Tcvt.Packages
{
    public partial class AddShelvesetsForm : Form
    {
        private VersionControlServer _versionControlServer;
        private DataGridViewSelectedRowCollection _selectedShelvesetRows;
        private int _maxSupportedShelvesets;
        private string _currentUser;
        private bool _allowMultipleShelvesets;
        private bool _enableShelvesetsPrequerying;
        private bool _enableCellContentClick;

        public AddShelvesetsForm()
        {
            InitializeComponent();
        }

        private void AddSelectedShelvesetButton_Click(object sender, EventArgs e)
        {
            int numSelected = this.SelectedShelvesetsDataGridView.SelectedRows.Count;
            if (numSelected <= 0)
            {
                Utils.ShowWarningMessageBox("There are no selected shelvesets to add.");
                return;
            }

            Utils.LogMessage(string.Format("AddSelectedShelvesetButton: Adding {0} shelvesets.", numSelected));
            _selectedShelvesetRows = this.SelectedShelvesetsDataGridView.SelectedRows;
            this.Close();
        }

        private void CancelShelvesetButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void FindButton_Click(object sender, EventArgs e)
        {
            FindShelvesets();
        }

        private void AddShelvesetsForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.OwnerNameTextBox.Text = string.IsNullOrEmpty(_currentUser) ? string.Empty : _currentUser;
                this.OwnerNameTextBox.Select();

                if (!_allowMultipleShelvesets)
                {
                    this.SelectedShelvesetsDataGridView.MultiSelect = false;
                }

                // Pre-query?
                if (_enableShelvesetsPrequerying)
                {
                    FindShelvesets();
                }
            }
            catch (Exception ex)
            {
                Utils.LogMessage("AddShelvesetsForm_Load: ErrorMessage:" + ex.Message);
                Utils.LogMessage("AddShelvesetsForm_Load: StackTrace:" + ex.StackTrace);
                Utils.ShowErrorMessageBox(string.Format("Error initializing 'Add Shelvesets' form:\r\n{0}",
                    ex.Message));
                this.Close();
            }
        }

        private void FindShelvesets()
        {
            string ownerName = this.OwnerNameTextBox.Text.Trim();
            if (ownerName.Length <= 0)
            {
                Utils.ShowWarningMessageBox("Please enter an owner name.");
                this.OwnerNameTextBox.Select();
                return;
            }

            this.PopulateShelvesets(ownerName);
        }

        private void PopulateShelvesets(string username)
        {
            this.SelectedShelvesetsDataGridView.Rows.Clear();

            try
            {
                Utils.LogMessage(string.Format("PopulateShelvesets: Pre-GetShelvesets [{0}].", username));
                Shelveset[] shelvesets = _versionControlServer.QueryShelvesets(null, username);
                Utils.LogMessage("PopulateShelvesets: Post-GetShelvesets.");
                if (shelvesets == null || shelvesets.Length == 0)
                {
                    Utils.LogMessage(string.Format("PopulateShelvesets: No shelvesets found for user '{0}'.", username));
                    Utils.ShowWarningMessageBox(string.Format("No shelvesets found for user '{0}'.", username));
                    return;
                }

                int numItemsFound = shelvesets.Length;
                
                Utils.LogMessage(string.Format("PopulateShelvesets: Found {0} shelvesets for user '{1}'.",
                    shelvesets.Length, username, numItemsFound));

                if (numItemsFound > MaxSupportedShelvesets && MaxSupportedShelvesets > 0)
                {
                    Utils.ShowErrorMessageBox(string.Format("You have {0} shelvesets. TFS Check-in Validaton Tool only supports {1} shelvesets. " +
                        "Please remove some shelvesets and try again.", numItemsFound, MaxSupportedShelvesets));
                    return;
                }

                string[] truncatedShelvesets = new string[numItemsFound];
                DataGridViewRow row = null;
                DataGridViewTextBoxCell cell = null;
                for (int i = 0; i < numItemsFound; i++)
                {
                    row = new DataGridViewRow();
                    
                    cell = new DataGridViewTextBoxCell();
                    cell.Value = shelvesets[i].Name;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = shelvesets[i].CreationDate;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = shelvesets[i].Comment;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = shelvesets[i].OwnerName;
                    row.Cells.Add(cell);

                    this.SelectedShelvesetsDataGridView.Rows.Add(row);

                    //int rowIndex = this.SelectedShelvesetsDataGridView.Rows.Count - 1; // last row.
                    //this.SelectedShelvesetsDataGridView.Rows[rowIndex].Cells[0].Value = shelvesets[i].Name;
                    //this.SelectedShelvesetsDataGridView.Rows[rowIndex].Cells[1].Value = shelvesets[i].CreationDate;
                    //this.SelectedShelvesetsDataGridView.Rows[rowIndex].Cells[2].Value = shelvesets[i].Comment;
                    //this.SelectedShelvesetsDataGridView.Rows[rowIndex].Cells[3].Value = shelvesets[i].OwnerName;
                }

                // Sort the list by date/time, descending.
                this.SelectedShelvesetsDataGridView.Sort(this.SelectedShelvesetsDataGridView.Columns[1],
                    System.ComponentModel.ListSortDirection.Descending);
            }
            catch (Exception ex)
            {
                Utils.LogMessage(string.Format("PopulateShelvesets: Error getting shelvesets: Message: {0}", ex.Message), LogType.Error);
                Utils.LogMessage(string.Format("PopulateShelvesets: Error getting shelvesets: StackTrace: {0}", ex.StackTrace), LogType.Error);
                Utils.ShowErrorMessageBox(string.Format("Error getting shelvesets:\r\n\r\n{0}",
                    ex.Message));
            }
            finally
            {
                this.RefreshControls();
            }
        }

        private void RefreshControls()
        {
            AddSelectedShelvesetButton.Enabled = (this.SelectedShelvesetsDataGridView.Rows.Count > 0);
        }

        public string CurrentUser
        {
            get
            {
                return _currentUser;
            }
            set
            {
                _currentUser = value;
            }
        }

        public int MaxSupportedShelvesets
        {
            get
            {
                return _maxSupportedShelvesets;
            }
            set
            {
                _maxSupportedShelvesets = value;
            }
        }

        public bool AllowMultipleShelvesets
        {
            get
            {
                return _allowMultipleShelvesets;
            }
            set
            {
                _allowMultipleShelvesets = value;
            }
        }

        public DataGridViewSelectedRowCollection SelectedShelvesetRows
        {
            get
            {
                return _selectedShelvesetRows;
            }
            set
            {
                _selectedShelvesetRows = value;
            }
        }

        public bool EnableShelvesetsPrequerying
        {
            get
            {
                return _enableShelvesetsPrequerying;
            }
            set
            {
                _enableShelvesetsPrequerying = value;
            }
        }

        public bool EnableCellContentClick
        {
            get
            {
                return _enableCellContentClick;
            }
            set
            {
                _enableCellContentClick = value;
            }
        }

        public VersionControlServer VersionControlServer
        {
            get
            {
                return _versionControlServer;
            }
            set
            {
                _versionControlServer = value;
            }
        }

        private void SelectedShelvesetsDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (!_enableCellContentClick)
                return; // Disable the clicking in the cell initiating a selection and returning to caller.

            int numSelected = this.SelectedShelvesetsDataGridView.SelectedRows.Count;
            if (numSelected != 1)
            {
                return;
            }

            Utils.LogMessage("SelectedShelvesetsDataGridView_CellContentClick: Adding 1 shelveset.");
            _selectedShelvesetRows = this.SelectedShelvesetsDataGridView.SelectedRows;
            this.Close();
        }
    }
}